package com.rbs.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
    static {
        Reader reader = null;
        try {
            //创建SqlSessionFactory对象。通过读取mybatis的主配置文件，能够创建SqlSessionFactory对象。
            // 需要SqlSessionFactory对象，使用Factory能获取SqlSession，有了SqlSession就能有dao，
            // 目的是获取dao对象，Factory创建需要读取mybatis主配置文件。
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static SqlSession getSession(){
        SqlSession session = tl.get();
        //获取SqlSession对象，需要使用SqlSessionFactory的openSession()方法
        if (session == null){
            session = sqlSessionFactory.openSession();
            tl.set(session);
        }
        return session;
    }
    //释放链接
    public static void colesSession(SqlSession session){
        if (session != null){
            session.close();
            tl.remove();
        }
    }
    public static void main(String[] args){
        SqlSession session = MybatisUtils.getSession();
        System.out.println(session);
    }
}
